<template>
  <a-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">
    
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
      
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="书名">
          <a-input placeholder="请输入书名" v-decorator="['bname', {rules:[{required:true,message:'书名不能为空'}]}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="作者">
          <a-input placeholder="请输入作者" v-decorator="['author', {rules:[{required:true,message:'作者不能为空'}]}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="原价">
          <a-input-number v-decorator="[ 'price', {rules:[{required:true,message:'原价不能为空'}]}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="当前价">
          <a-input-number v-decorator="[ 'currPrice', {rules:[{required:true,message:'当前价不能为空'}]}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="折扣">
          <a-input-number v-decorator="[ 'discount', {}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="出版社">
          <a-input placeholder="请输入出版社" v-decorator="['press', {rules:[{required:true,message:'出版社不能为空'}]}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="出版时间">
          <a-date-picker showTime format='YYYY-MM-DD HH:mm:ss' v-decorator="[ 'publishTime', {rules:[{required:true,message:'出版时间不能为空'}]}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="版次">
          <a-input placeholder="请输入版次" v-decorator="['edition', {rules:[{required:true,message:'版次不能为空'}]}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="页数">
          <a-input-number v-decorator="[ 'pageNum', {rules:[{required:true,message:'页数不能为空'}]}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="字数">
          <a-input-number v-decorator="[ 'wordNum', {rules:[{required:true,message:'字数不能为空'}]}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="印刷时间">
          <a-date-picker showTime format='YYYY-MM-DD HH:mm:ss' v-decorator="[ 'printTime', {rules:[{required:true,message:'印刷时间不能为空'}]}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="开本">
          <j-dict-select-tag  v-decorator="['booksize', {rules:[{required:true,message:'请选择开本'}]}]"  :triggerChange="true" placeholder="请选择开本" dictCode="bz"/>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="纸质">
          <a-input placeholder="请输入纸质" v-decorator="['page', {}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="所属分类">
        <a-select
            v-decorator="['cid',{rules:[{required:true,message:'请选择所属分类'}]}]" style="width: 50%">
            <a-select-option v-for="(category,index) in childrenOptions" :key="index" :value="category.id">
                  <span :title="category.categoryName">
                    {{ category.categoryName }}
                  </span>
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="大图">
          <a-upload
            v-decorator="['imgBig', {rules:[{required:true,message:'请选择上传图片'}]}]"
            name="avatar"
            listType="picture-card"
            class="avatar-uploader"
            :showUploadList="false"
            action
            :customRequest="upload"
            :beforeUpload="beforeUpload"
            @change="handleChange"
          >
            <img v-if="imageUrl" :src="imageUrl" alt="avatar"/>
            <div v-else>
              <a-icon :type="loading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">Upload</div>
            </div>
          </a-upload>
        </a-form-item>
        
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="类型">
          <j-dict-select-tag  v-decorator="['type', {rules:[{required:true,message:'请选择类型'}]}]"  :triggerChange="true" placeholder="请选择类型" dictCode="type"/>
        </a-form-item>

         <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="数量">
          <a-input-number v-decorator="[ 'num', {rules:[{required:true,message:'数量不能为空'}]}]" />
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="是否上架">
          <j-dict-select-tag
            :triggerChange="true"
            v-decorator="['status', {}]"
            dictCode="sf"
          />
        </a-form-item>
		
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
  import { httpAction , postAction } from '@/api/manage'
  import { getAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import moment from "moment"

  export default {
    name: "BookModal",
    data () {
      return {
        title:"操作",
        visible: false,
        model: {},
        loading: false,
        imageUrl:'',
        status: 0,
        parentsOptions: [],
        childrenOptions: [],
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },

        confirmLoading: false,
        form: this.$form.createForm(this),
        validatorRules:{
        },
        url: {
          add: "/book/book/add",
          edit: "/book/book/edit",
        },
      }
    },
    created () { 
      this.loadchildren()
    },
    methods: {
      loadchildren(){
        getAction('/book/category/allChildren', 'get').then((res) => {
          if (res.success) {
            // 设置二级分类信息
            this.childrenOptions = res.result
          } else {
            this.$message.warning(res.message)
          }
        })
      },
      add () {
        this.edit({});
      },
      edit (record) {
        this.form.resetFields();
        this.model = Object.assign({}, record);
        this.imageUrl = this.model.imgBig;
        this.visible = true;
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model,'bname','author','price','currPrice','discount','press','edition','pageNum','wordNum','booksize','page','cid','imgBig','imgSmall','type','status'))
		  //时间格式化
          this.form.setFieldsValue({publishTime:this.model.publishTime?moment(this.model.publishTime):null})
          this.form.setFieldsValue({printTime:this.model.printTime?moment(this.model.printTime):null})
        });

      },
      close () {
        this.$emit('close');
        this.visible = false;
      },
			
      handleOk () {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            let formData = Object.assign(this.model, values);
            //时间格式化
            formData.publishTime = formData.publishTime?formData.publishTime.format('YYYY-MM-DD HH:mm:ss'):null;
            formData.printTime = formData.printTime?formData.printTime.format('YYYY-MM-DD HH:mm:ss'):null;
            formData.imgBig = this.imageUrl;
            console.log(formData)
            httpAction(httpurl,formData,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })



          }
        })
      },
      handleCancel () {
        this.close()
      },

      uploadChange(info) {
      if (info.file.status === 'uploading') {
        this.loading = true
        return
      }
      if (info.file.status === 'done') {
        getBase64(info.file.originFileObj, imageUrl => {
          this.imgBig = imageUrl
          this.loading = false
        })
      }
    },
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png'
      if (!isJPG) {
        this.$message.error('请上传jpeg、jpg、png格式的图片!')
      }
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isLt5M) {
        this.$message.error('图片必须小于 5MB!')
      }
      return isJPG && isLt5M
    },
    upload(data) {
      const formData = new FormData()
      let _this = this
      formData.append('file', data.file)
      postAction('/oss/file/upload', formData).then(res => {
        if (res.success && res.code == 200) {
          _this.imageUrl = res.result.url
          _this.$message.success('上传成功！', 3)
        } else {
          _this.$message.error('上传失败！', 3)
        }
      })
    }
  }

    
  }
</script>

<style lang="less" scoped>

</style>